import { logout, phoneLogin, passwordLogin } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { getUserInfo } from '@/api/common'
import { queryById } from '@/api/colleague'
import router, { resetRouter } from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  companyId: '',
  companyInfo: null,
  userInfo: null
}

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_COMPANYID: (state, id) => {
    state.companyId = id
  },
  SET_COMPANYINFO: (state, obj) => {
    state.companyInfo = obj
  },
  SET_USERINFO: (state, obj) => {
    state.userInfo = obj
  }
}

const actions = {
  // user login
  login({ commit }, form) {
    return new Promise((resolve, reject) => {
      if (form.loginMode == 1) { // 密码登录
        passwordLogin(form).then(res => {
          if (res.result.token) {
            commit('SET_TOKEN', res.result.token)
            setToken(res.result.token)
            resolve(res.result)
            this.$message.success('登录成功')
          }
        }).catch(error => {
          reject(error)
        })
      } else {
        phoneLogin(form).then(res => {
          if (res.result.token) {
            commit('SET_TOKEN', res.result.token)
            setToken(res.result.token)
            resolve(res.result)
            this.$message.success('登录成功')
          }
        }).catch(error => {
          reject(error)
        })
      }
      // 登录接口
    })
  },

  // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         reject('Verification failed, please Login again.')
  //       }

  //       const { roles, name, avatar, introduction } = data

  //       // roles must be a non-empty array
  //       if (!roles || roles.length <= 0) {
  //         reject('getInfo: roles must be a non-null array!')
  //       }

  //       commit('SET_ROLES', roles)
  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       commit('SET_INTRODUCTION', introduction)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      // const data = { roles: ['admin'] }
      // const { roles } = data
      // commit('SET_ROLES', roles)
      // resolve(data)
      getUserInfo().then(response => {
        const data = { roles: ['admin'] }
        const { roles } = data
        const res = response.result
        data.reg = res.reg
        data.enState = res.enState
        if (res.enInfo) {
          const enInfo = res.enInfo
          enInfo.enTrade ? enInfo.enTrade = enInfo.enTrade.split(',') : null
          enInfo.enAddress ? enInfo.enAddress = enInfo.enAddress.split(',') : null
          enInfo.otherWelfare ? enInfo.otherWelfare = enInfo.otherWelfare.split(',') : null
          commit('SET_NAME', enInfo.enName)
          commit('SET_AVATAR', enInfo.enLogo_dictText)
          commit('SET_COMPANYID', enInfo.id)
          commit('SET_COMPANYINFO', res)
        }
        console.log(data)
        if (parseFloat(res.enState) === 0) {
          commit('SET_ROLES', roles)
        }
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  getUserInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      queryById({ id: state.companyInfo.id }).then(response => {
        const data = response.result
        commit('SET_USERINFO', data)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      logout().then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()
        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        // dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
